<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" align-center
        style="width:90%;min-height:90%;">
        <div class="app-body">
            <el-tabs type="border-card">
                <el-tab-pane :label="'未盘点' + total" @click="handleTabsEdit">
                    <div class="app-search">
                        <el-form :inline="true" class="demo-form-inline" v-model="form">
                            <el-form-item label="资产名称">
                                <el-input placeholder="请输入资产名称" style="width: 200px;" v-model="form.name"></el-input>
                            </el-form-item>
                            <el-form-item label="财政编号">
                                <el-input placeholder="请输入财政编号" style="width: 200px;" v-model="form.oldCode"></el-input>
                            </el-form-item>
                            <el-form-item label="购进日期">
                                <el-date-picker v-model="form.purchaseDate" style="width: 200px;" type="date"
                                    placeholder="请选择购进日期" value-format="YYYY-MM-DD" @change="changeTime" />
                            </el-form-item>
                            <el-form-item label="使用人">
                                <el-input placeholder="请输入使用人" style="width: 200px;"
                                    v-model="form.useTeacher"></el-input>
                            </el-form-item>
                            <!-- <el-form-item label="盘点部门">
                                <el-select v-model="form.department" placeholder="请选择盘点部门" style="width: 200px;"
                                    filterable :filter-method="serachDepartment" clearable @change="changeDepartment">
                                    <el-option v-for="item in departmentList" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item> -->
                            <el-form-item label="校区">
                                <el-select v-model="myCampus" clearable style="width: 200px;" placeholder="请选择校区">
                                    <el-option v-for="item in campusOptions" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button class="serach_btn" type="primary" @click="onSubmit"
                                    @keyup.enter="searchEnter">搜索</el-button>
                                <el-button class="add_btn" type="success" @click="allCheckAssets">一键盘点</el-button>
                                <el-button class="add_btn" type="success" @click="exportHandle(0)">导出资产</el-button>
                                <!-- <el-button class="add_btn" type="success" @click="importHandle">导入更新</el-button>
                                <input class="file" ref="file" type="file" :accept="excelAccept"
                                    @change="handleChangeFile" style="display: none;"> -->
                                <el-upload ref="uploadRef" class="upload-demo" :show-file-list="false"
                                    :on-change="handleChangeFile" :auto-upload="false">
                                    <template #trigger>
                                        <el-button class="add_btn" style="width: 90px;margin-left: 10px;"
                                            type="success">导入更新</el-button>
                                    </template>
                                </el-upload>
                            </el-form-item>
                        </el-form>
                    </div>
                    <el-table :data="list" style="width: 100%" @selection-change="selectAll">
                        <el-table-column type="selection" width="30" @select-all="selectAll1" />
                        <el-table-column prop="id" label="id" width="100" />
                        <el-table-column prop="name" label="资产名称" width="150" />
                        <el-table-column prop="code" label="资产编号" width="150" />
                        <el-table-column prop="oldCode" label="财政编号" width="150" />
                        <el-table-column prop="purchaseDate" label="购进日期" width="110" />
                        <!-- <el-table-column prop="department" label="使用部门" width="110" /> -->
                        <el-table-column prop="useTeacher" label="使用人" width="150">
                            <template style="display: block" #default="scope">
                                <el-select v-model="scope.row.useTeacher" filterable :filter-method="serachTeacher"
                                    placeholder="请选择使用人 " style="width:100%"
                                    @change="changeTeacher(scope.row.id, scope.row.useTeacher)"
                                    @focus="focusHandle(scope.row.useTeacher)">
                                    <el-option v-for="item in teacherList" :key="item.id" :label="item.name"
                                        :value="item.name" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="department" label="使用部门" width="170">
                            <!-- <template style="display: block" #default="scope">
                                <el-select v-model="scope.row.department" placeholder="请选择使用部门" style="width:100%"
                                    filterable :filter-method="serachDepartment" clearable @change="changeDepartment1">
                                    <el-option v-for="item in departmentAllList" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </template> -->
                        </el-table-column>
                        <el-table-column prop="place" label="存放地点" width="200">
                            <template style="display: block" #default="scope">
                                <el-cascader :placeholder="getStoreAdress(scope.row.place)" :options="addresslist"
                                    filterable v-model="scope.row.place" @change="handleChangePlace" />

                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" width="220">
                            <template style="display: block" #default="scope">
                                <el-input placeholder="请输入备注" v-model="scope.row.remark" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="managerDepartment" label="管理部门" width="120">
                            <!-- <template style="display: block" #default="scope">
                                <el-select v-model="scope.row.managerDepartment" placeholder="请选择管理部门"
                                    style="width:100%" filterable :filter-method="serachDepartment" clearable
                                    @change="changeDepartment">
                                    <el-option v-for="item in departmentList" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </template> -->
                        </el-table-column>

                        <el-table-column label="存放校区" width="200">
                            <template style="display: block" #default="scope">
                                <el-radio-group v-model="scope.row.campus">
                                    <el-radio :value="1" :label="1">{{ campusName }}</el-radio>
                                    <el-radio :value="2" :label="2">{{ campusName1 }}</el-radio>
                                </el-radio-group>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="80px" fixed="right">
                            <template style="display: block" #default="scope">
                                <div style="display: flex;">
                                    <div>
                                        <el-button class="edit_btn" size="small" type="success"
                                            @click="checkAssets(scope.row, 1)">盘点
                                        </el-button>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <template v-slot:empty>
                            <el-empty description="暂无数据"></el-empty>
                        </template>
                    </el-table>

                    <el-config-provider :locale="locale" style="margin-top: 10px;">
                        <el-pagination :total="total" :page-size="limit" :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                            layout="total, sizes, prev, pager, next, jumper" @size-change="changePageSize"
                            @current-change="changeCurrentPage">
                        </el-pagination>
                    </el-config-provider>
                </el-tab-pane>
                <el-tab-pane :label="'已盘点' + total1" @click="handleTabsEdit1">
                    <div class="app-search">
                        <el-form :inline="true" class="demo-form-inline" v-model="form">
                            <el-form-item label="资产名称">
                                <el-input placeholder="请输入资产名称" v-model="form.name"></el-input>
                            </el-form-item>
                            <el-form-item label="财政编号">
                                <el-input placeholder="请输入财政编号" style="width: 200px;" v-model="form.oldCode"></el-input>
                            </el-form-item>
                            <el-form-item label="购进日期">
                                <el-date-picker v-model="form.purchaseDate" type="date" placeholder="请选择购进日期" />
                            </el-form-item>
                            <el-form-item>
                                <el-button class="serach_btn" type="primary" @click="onSubmit1"
                                    @keyup.enter="searchEnter">搜索</el-button>
                                <el-button class="add_btn" type="success" @click="exportHandle(1)">导出资产</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                    <el-table :data="list1" style="width: 100%">
                        <el-table-column prop="id" label="id" width="100" />
                        <el-table-column prop="name" label="资产名称" width="150" />
                        <el-table-column prop="code" label="资产编号" width="150" />
                        <el-table-column prop="oldCode" label="财产编号" width="150" />
                        <el-table-column prop="purchaseDate" label="购进日期" width="110" />
                        <el-table-column label="存放校区">
                            <template style="display: block" #default="scope">
                                <span v-if="scope.row.campus == 1">{{ campusName }}</span>
                                <span v-if="scope.row.campus == 2">{{ campusName1 }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="place" label="存放地点" />
                        <el-table-column prop="department" label="使用部门" width="110" />
                        <el-table-column prop="useTeacher" label="使用人" />
                        <el-table-column prop="managerDepartment" label="管理部门" />
                        <el-table-column prop="manager" label="管理人" />
                        <el-table-column prop="remark" label="备注" />
                        <el-table-column prop="updateTeacherName" label="盘点人" />
                        <el-table-column label="操作" width="80px" fixed="right">
                            <template style="display: block" #default="scope">
                                <div style="display: flex;">
                                    <!-- <div> -->
                                    <el-button class="edit_btn" size="small" type="success"
                                        @click="checkAssets(scope.row, 0)">改为未盘
                                    </el-button>
                                    <!-- </div> -->
                                </div>
                            </template>
                        </el-table-column>
                        <template v-slot:empty>
                            <el-empty description="暂无数据"></el-empty>
                        </template>
                    </el-table>
                    <el-config-provider :locale="locale" style="margin-top: 10px;">
                        <el-pagination :total="total1" :page-size="limit1" :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
                            layout="total, sizes, prev, pager, next, jumper" @size-change="changePageSize1"
                            @current-change="changeCurrentPage1">
                        </el-pagination>
                    </el-config-provider>
                </el-tab-pane>

            </el-tabs>
        </div>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm, ElMessageBox, ElLoading } from "element-plus";
import { vxRule } from "@/utils/validator";
import formatTime from "@/utils/dateFormat.js";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { API_BASE_NAME2, API_BASE_NAME3, API_BASE_NAME, API_BASE_NAME1 } from '../../constants';

export default {
    name: "AddBaseAddress",
    components: { ElForm, ElMessage },
    data() {
        return {
            campusName: API_BASE_NAME2,
            campusName1: API_BASE_NAME3,
            dialogFormVisible: ref(false),
            formLabelWidth: "120px",
            title: "",
            personnelType: "",
            id: '',
            campus: 1,
            data: {},
            page: 1,
            pageSize: 10,
            page1: 1,
            pageSize1: 10,
            total: 0,
            limit: 10,
            limit1: 10,
            list: [],
            list1: [],
            total1: 0,
            teacherList: [],
            allId: '',
            departmentList: [],
            departmentAllList: [],
            user: {},
            nowTeacher: "",
            oldTeacher: "",
            myCampus: "",
            // userCampus: '',
            form: {
                id: "",
                name: '',
                purchaseDate: "",
                flag: 0,
                useTeacher: "",
                department: "",
                oldCode: "",
            },
            addTaskForm: {
                useTeacher: '',
                place: '',
                campus: '',
                department: '',
            },
            campusOptions: [
                {
                    label: API_BASE_NAME2,
                    value: 1
                },
                {
                    label: API_BASE_NAME3,
                    value: 2
                },
            ]
            // 校验规则
            // addBaseTaskrules: {
            //     name: vxRule(true, null, "blur"),
            // },
        };
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    mounted() {
        // this.data = this.addBasePanForm
        // if (this.title == '新增') {
        //     this.clear()
        // }
        // console.log(formatTime(new Date()));
        this.user = JSON.parse(sessionStorage.getItem('user'))
        this.getDepartmentAllList()
    },
    watch: {
        data(newValue) {
            this.addBasePanForm = newValue
        },
    },


    methods: {
        searchEnter: function (e) {
            // 使用 which 和 keyCode 属性来解决兼容问题
            var keyCode = window.event ? e.keyCode : e.which;
            var val = e.target.value;
            if (keyCode == 13 && val) {
                this.getInventoryList(this.id);
            }
        },
        onSubmit() {
            this.getInventoryList(this.id);
        },
        onSubmit1() {
            this.getInventoryList1(this.id);
        },
        getStoreAdress(str) {
            return str ? str : '请选择存放地点'
        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.dialogFormVisible = false;
            this.clear();
        },
        changeTime(value) {
            if (value == null) {
                this.form.purchaseDate = ""
            }
        },
        getInventoryList(id) {
            this.list = []
            httpService("/javaApi/faSubListInventory/list/" + this.page + "/" + this.pageSize, {
                "taskId": id,
                "purchaseDateStr": this.form.purchaseDate ? this.form.purchaseDate : "",
                "name": this.form.name,
                "flag": 0,
                "useTeacher": this.form.useTeacher,
                "department": this.form.department,
                "campus": this.myCampus ? this.myCampus : "",
                "oldCode": this.form.oldCode,
            }, "get").then(
                (data) => {
                    if (data.list) {
                        // data.list.map(item => item.purchaseDate = item.purchaseDate.slice(0, 10) && item.useTeacher.split(",")[item.useTeacher.split(",").length - 1])
                        data.list = data.list.map(item => {
                            if (item.purchaseDate && item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate.slice(0, 10),
                                    useTeacher: item.useTeacher.split(",")[item.useTeacher.split(",").length - 1]
                                }
                            } else if (!item.purchaseDate && item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate,
                                    useTeacher: item.useTeacher.split(",")[item.useTeacher.split(",").length - 1]
                                }
                            } else if (item.purchaseDate && !item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate.slice(0, 10),
                                    useTeacher: item.useTeacher
                                }
                            } else {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate,
                                    useTeacher: item.useTeacher
                                }
                            }
                        })
                        data.list.map(item => {
                            if (!item.campus) {
                                item.campus = this.user.campus
                            }
                        })
                        this.list = data.list;
                        this.total = data.total
                    }
                }
            );
        },
        getInventoryList1(id) {
            this.list1 = []
            httpService("/javaApi/faSubListInventory/list/" + this.page1 + "/" + this.pageSize1, {
                "taskId": id, "name": this.form.name,
                "purchaseDateStr": this.form.purchaseDate,
                "flag": 1,
                "oldCode": this.form.oldCode,
            }, "get").then(
                (data) => {
                    if (data.list) {
                        data.list = data.list.map(item => {
                            if (item.purchaseDate && item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate.slice(0, 10),
                                    useTeacher: item.useTeacher.split(",")[item.useTeacher.split(",").length - 1]
                                }
                            } else if (!item.purchaseDate && item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate,
                                    useTeacher: item.useTeacher.split(",")[item.useTeacher.split(",").length - 1]
                                }
                            } else if (item.purchaseDate && !item.useTeacher) {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate.slice(0, 10),
                                    useTeacher: item.useTeacher
                                }
                            } else {
                                return {
                                    ...item,
                                    purchaseDate: item.purchaseDate,
                                    useTeacher: item.useTeacher
                                }
                            }
                        })

                        this.list1 = data.list;
                        this.total1 = data.total
                    }
                }
            );
        },
        clear() {
            this.dialogFormVisible = false;
            //清空form
            this.title = ''
            this.id = ''
            this.list = []
            this.list1 = []
            this.page = 1
            this.page1 = 1
            this.pageSize = 10
            this.limit = ""
            this.form.id = ""
            this.form.name = ''
            this.form.purchaseDate = ""
            this.form.flag = 0
            this.form.useTeacher = ""
            this.form.department = ""
            this.total = 0
            this.total1 = 0
            this.$refs.uploadRef.clearFiles();
        },
        checkAssets(data, number) {
            if ((this.nowTeacher && this.oldTeacher) && (this.nowTeacher != this.oldTeacher)) {
                data.useTeacher = this.oldTeacher + "," + this.nowTeacher
            }
            // console.log(data.department);
            data.useTeacher ? data.useTeacher = data.useTeacher : data.useTeacher = ""
            this.addTaskForm.place ? this.addTaskForm.place = this.addTaskForm.place : this.addTaskForm.place = ""
            data.remark ? data.remark = data.remark : data.remark = ""

            let params = new FormData();
            params.append("id", data.id)
            params.append("useTeacher", data.useTeacher)
            params.append("department", data.department)
            params.append("place", this.addTaskForm.place)
            params.append("campus", data.campus)
            params.append("remark", data.remark)
            params.append("flag", number)
            if (this.addTaskForm.department) {
                params.append("department", this.addTaskForm.department)
            }
            httpService(
                "/javaApi/faSubListInventory/edit", params, "post"
            ).then((data) => {
                this.dialogFlag = false
                if (data.code == 200) {
                    ElMessage.success("盘点成功");
                    this.getInventoryList(this.id)
                    this.getInventoryList1(this.id)
                    this.addTaskForm.department = ''
                } else {
                    ElMessage.error("盘点失败");
                }
            });
        },
        changePageSize(size) {
            this.pageSize = size;
            this.limit = size;
            this.getInventoryList(this.id);
        },
        // 改变页码，page：回调参数，表示当前选中的“页码”
        changeCurrentPage(page) {
            this.page = page;
            this.getInventoryList(this.id);
        },

        changePageSize1(size) {
            this.pageSize1 = size;
            this.limit1 = size;
            this.getInventoryList1(this.id);
        },
        changeCurrentPage1(page) {
            this.page1 = page;
            this.getInventoryList1(this.id);
        },

        getBaseTeacherList() {
            httpService(
                "/javaApi/baseTeacher/list/1/10000",
                {},
                "get"
            ).then((data) => {
                this.teacherList = data.list;
            });
        },
        serachTeacher(value) {
            let teacher = ''
            value == undefined ? teacher = '' : teacher = value
            httpService("/javaApi/baseTeacher/list/1/10000", { "name": teacher }, "get").then(
                (data) => {
                    this.teacherList = data.list
                }
            );
        },
        getAddressList() {
            httpService(
                "/javaApi/baseAddress/list/1/10000",
                {
                    // campus: this.user.campus,
                }, "get"
            ).then((data) => {
                if (data.list) {
                    data.list.forEach(item => item.children = []);
                }

                const arr = data.list.map(item => {
                    const { alias, ...rest } = item;
                    return { label: alias, value: alias, ...rest };
                });

                this.addresslist = this.buildTree(arr)
            });
        },

        buildTree(items) {

            const idMap = {};
            const tree = [];
            items.forEach(item => {
                idMap[item.id] = { ...item, children: [] };
            });
            items.forEach(item => {
                const parentId = item.parentId;
                const currentNode = idMap[item.id];

                if (parentId === 0) {
                    tree.push(currentNode);
                } else {
                    const parent = idMap[parentId];
                    if (parent) {
                        parent.children.push(currentNode);
                    }
                }
            });

            if (tree.length > 0) {
                return tree[0].children
            }
            // if (this.user.campus == 1) {
            //     return tree[1].children
            // } else if (this.user.campus == 2) {
            //     return tree[0].children
            // } 
        },



        handleChangePlace(value) {
            this.addTaskForm.place = value.join("-")
        },
        allCheckAssets() {
            let params = new FormData();
            params.append("ids", this.allId)
            // params.append("flag", 1)
            httpService(
                "/javaApi/faSubListInventory/updateBatch", params, "post"
            ).then((data) => {
                if (data.code == 200) {
                    ElMessage.success("盘点成功");
                    this.getInventoryList(this.id)
                    this.getInventoryList1(this.id)
                } else {
                    ElMessage.error("盘点失败");
                }
            });
        },
        selectAll(value) {
            let str = []
            value.forEach(item => {
                str.push(item.id)
            })
            this.allId = str.join(",")
        },

        exportHandle(number) {
            var loadingInstance = ElLoading.service({
                lock: true, text: '加载中', background: 'rgba(0, 0, 0, 0.7)',
            });
            httpService(
                "/javaApi/faSubListInventory/exportExcel",
                {
                    taskId: this.id,
                    flag: number,
                },
                "get"
            ).then((data) => {
                loadingInstance.close()
                if (data.code == 200) {
                    window.open(data.message, "_blank");
                    // window.open("http://192.168.9.20" + data.message, "_blank");
                    // window.location.href = data.message
                }
            });
        },
        importHandle() {
            this.$refs.file.click()
        },
        handleChangeFile(e) {
            let file = e.raw
            if (file) {
                ElMessageBox.confirm("确定要导入更新吗", "提醒", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    var loadingInstance = ElLoading.service({
                        lock: true, text: '加载中', background: 'rgba(0, 0, 0, 0.7)',
                    });
                    let params = new FormData()
                    params.append('file', file)
                    httpService("/javaApi/faSubListInventory/importExcel", params, "post").then(
                        (data) => {
                            loadingInstance.close()
                            if (data.code == 200) {
                                ElMessage.success("导入盘点成功");
                                this.getInventoryList(this.id)
                                this.getInventoryList1(this.id)
                            } else {
                                ElMessage.error("导入盘点失败");
                            }
                        }
                    );
                })
            } else {
            }

        },
        getDepartmentAllList() {
            httpService("/javaApi/baseDepartment/list/1/200", { "name": this.form.department }, "get").then(
                (data) => {
                    this.departmentAllList = data.list
                }
            );
        },
        getDepartmentList() {
            httpService("/javaApi/faDepartment/list/1/100", { "name": this.form.department }, "get").then(
                (data) => {
                    this.departmentList = data.list
                }
            );
        },
        serachDepartment(value) {
            // console.log(value);
            // this.form.department
            // this.getDepartmentList()
            // this.departmentList = this.departmentList.filter(item => {
            //     return item.name.indexOf(value)
            // })
        },
        changeDepartment(value) {
            if (this.departmentList) {
                this.form.department = this.departmentList.filter(item => item.id == value)[0].name
            }
        },
        changeDepartment1(value) {
            console.log(123, value);
            if (this.departmentAllList) {

                const arr = this.departmentAllList.filter(item => item.id == value)

                this.addTaskForm.department = arr[0].name
                console.log(this.addTaskForm.department);

            }
        },
        changeTeacher(id, str) {
            let teacherData = []
            if (this.teacherList) {
                teacherData = this.teacherList.filter(item => item.name == str)
                if (teacherData.length > 0) {
                    this.nowTeacher = teacherData[0].name
                    const index = this.list.findIndex(item => item.id === id);
                    if (index !== -1) {
                        this.list[index].department = teacherData[0].departmentNames
                    }
                }
            }
        },
        focusHandle(data) {
            this.oldTeacher = data
        },
    }
};
</script>
<style scoped>
.el-table {
    margin-bottom: 20px;
}

.add_btn {
    background-color: #00c78c;
    color: #fff;
    border-radius: 8px;
    border: none;
}

.el-tabs {
    height: 100%;
}

.el-dialog__header {
    padding: var(--el-dialog-padding-primary);
    padding-bottom: 10px;
    border-bottom: 1px solid #dedede;
    margin-bottom: 15px;
}
</style>